package com.tsu.mall.common.util;


import com.tsu.mall.common.entity.Member;
import org.springframework.cglib.core.Local;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Locale;

//请求工具类
public class RequestUtil {
    private static final String CURRENT_KEY = "CURRENT_MEMBER";

   // 调用此静态方法直接返回这次请求的request对象
    public static HttpServletRequest getRequest(){
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }
    //返回此次请求的Session对象
    public  static HttpSession getSession(){
        return getRequest().getSession();
    }

    //获取前台当前的登录的会员对象
    public static Member getCurrent(){
        Object obj=RequestUtil.getSession().getAttribute(CURRENT_KEY);
        if (obj == null) {
            return null;
        }
        return (Member) obj;
    }

    public static void setCurrent(Member member){
        RequestUtil.getSession().setAttribute(CURRENT_KEY,member);
    }

    //接收一个语言，保存到session中
    public static void setLan(String lan) {
        Locale locale= LocaleContextHolder.getLocale();
        if("zh".equals(lan)){
            locale=new Locale("zh","CN");
        }
        if("en".equals(lan)){
            locale=new Locale("en","US");
        }
        getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
    }
}
